package com.mimo.comet.controller;

import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mimo.comet.dao.ISessionDao;
import com.mimo.comet.user.service.IUserService;
import com.mimo.common.dto.Entry;
import com.mimo.common.result.BaseResult;

import io.swagger.annotations.ApiOperation;

@Validated
@RestController
@RequestMapping("/session")
public class SessionController {

  @Autowired
  private ISessionDao sessionDao;

  @Autowired
  private IUserService userService;

  @GetMapping("/list")
  public Object listAllSessions() {
    return sessionDao.listAll().stream().map(s -> new Entry<>(s.getCometType(), s.getSessionId()))
        .collect(Collectors.toList());
  }

  @GetMapping("/load/{sessionId}")
  public Object loadBySessionId(@PathVariable String sessionId) {
    return sessionDao.findByUid(sessionId).orElse(null);
  }

  @PostMapping("/close/{sessionId}")
  @ApiOperation(value = "强制关停本地会话连接", response = BaseResult.class)
  public Object closeSession(@PathVariable String sessionId) {
    userService.unbinding(sessionId, null);
    return BaseResult.SUCCESS_RET;
  }

}
